"""JSON编码器工具"""

import json
from typing import Any
from enum import Enum
from pydantic import BaseModel


class BattleJSONEncoder(json.JSONEncoder):
    """战斗游戏专用JSON编码器"""
    
    def default(self, obj: Any) -> Any:
        """自定义对象序列化"""
        
        # 处理Pydantic模型
        if isinstance(obj, BaseModel):
            return obj.model_dump()
        
        # 处理枚举类型
        if isinstance(obj, Enum):
            return obj.value
        
        # 处理其他类型
        return super().default(obj)


def to_json(obj: Any, indent: int = 2, ensure_ascii: bool = False) -> str:
    """将对象转换为JSON字符串"""
    return json.dumps(obj, cls=BattleJSONEncoder, indent=indent, ensure_ascii=ensure_ascii)


def format_battle_result(battle_result: dict) -> str:
    """格式化战斗结果为美观的JSON"""
    return to_json(battle_result, indent=2)


def save_battle_result(battle_result: dict, filename: str) -> bool:
    """保存战斗结果到文件"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(format_battle_result(battle_result))
        return True
    except Exception as e:
        print(f"保存文件失败: {e}")
        return False